﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CnGine.CodeGenerator.Forms
{
    public partial class FormDB : Form
    {


        DataTable dtServer = new DataTable();
        Help.ServerHelper help = new Help.ServerHelper();
        public FormDB()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 初始化操作
        /// </summary>
        private void FormDB_Load(object sender, EventArgs e)
        {
            try
            {
                string path = Help.DTEHelper.GetProjectPath();
            }
            catch
            {
                throw new Exception("请选一个要生成的项目或类库....");
            }

            //加载服务器列表信息
            help.XmlPath = Help.CommHelper.GetAssemblyPath() + @"\Config\Server.xml";
            LoadServer();
        }

        public void LoadServer()
        {

            txtServer.Text = "";
            txtUserName.Text = "";
            txtPassword.Text = "";

            btnUpdateServer.Enabled = false;
            btnDeleteServer.Enabled = false;
            btnNext.Enabled = false;
            Succ("");

            dtServer = help.Read();
            if (lstServer.Items.Count > 0)
            {
                lstServer.Items.Clear();
            }
            if (dtServer != null && dtServer.Rows.Count > 0)
            {
                foreach (DataRow r in dtServer.Rows)
                {
                    string ip = "";
                    if (r["ip"] != null) ip = r["ip"].ToString();
                    lstServer.Items.Add(ip);
                }
            }
        }
        private void btnAddServer_Click(object sender, EventArgs e)
        {
            UpdateServer(false);
            LoadServer();
        }
        /// <summary>
        /// 添加或者更新服务器信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdateServer_Click(object sender, EventArgs e)
        {
            UpdateServer(true);
            LoadServer();
        }

        private void btnDeleteServer_Click(object sender, EventArgs e)
        {
            string ip = txtServer.Text.Trim();
            help.Delete(ip);
            LoadServer();
        }

        public void UpdateServer(bool delete)
        {
            string server = txtServer.Text.Trim();
            string username = txtUserName.Text.Trim();
            string password = txtPassword.Text.Trim();

            if (string.IsNullOrEmpty(server))
            {
                Error("错误：请输入服务器名称");
                txtServer.Focus();
                return;
            }
            if (string.IsNullOrEmpty(username))
            {
                Error("错误：请输入登录名");
                txtUserName.Focus();
                return;
            }
            Succ("");
            help.Update(server, username, password);
            if (delete)
            {
                //如果是更新的话删除就的服务器信息
                string oldIP = lstServer.SelectedItem.ToString();
                //如果服务器信息不相等的话则删除旧的服务器信息
                if (!oldIP.Equals(server))
                {
                    help.Delete(oldIP);
                }
            }
        }


        public void Error(string msg)
        {
            lblMsg.ForeColor = Color.Red;
            lblMsg.Text = string.Format("{0}", msg);
        }
        public void Succ(string msg)
        {
            lblMsg.ForeColor = Color.Green;
            lblMsg.Text = string.Format("{0}", msg);

        }

        private void lstServer_Click(object sender, EventArgs e)
        {
            if (lstServer.SelectedItem != null && !string.IsNullOrEmpty(lstServer.SelectedItem.ToString()))
            {
                string ip = lstServer.SelectedItem.ToString();
                foreach (DataRow r in dtServer.Rows)
                {
                    string tip = "";
                    if (r["ip"] != null) tip = r["ip"].ToString();
                    if (tip == ip)
                    {
                        txtServer.Text = tip;
                        txtUserName.Text = r["username"].ToString();
                        txtPassword.Text = r["password"].ToString();

                        btnDeleteServer.Enabled = true;
                        btnUpdateServer.Enabled = true;
                        btnNext.Enabled = true;
                        break;
                    }
                }
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (lstServer.SelectedItem != null && !string.IsNullOrEmpty(lstServer.SelectedItem.ToString()))
            {
                string ip = lstServer.SelectedItem.ToString();
                UpdateServer(true);
                LoadServer();
                lstServer.SelectedValue = ip;

                foreach (DataRow r in dtServer.Rows)
                {
                    string tip = "";
                    if (r["ip"] != null) tip = r["ip"].ToString();
                    if (tip == ip)
                    {
                        //测试数据库服务器是否能链接，如果能链接则忘下一步，是否提示错误信息
                        string connectionStr = string.Format(@"server={0};uid={1};pwd={2};", ip, r["username"].ToString(), r["password"].ToString());
                        string connectionTimeOut = connectionStr + "Connect Timeout=5;";
                        if (Help.SQLHelper.TestConnection(connectionTimeOut))
                        {
                            Help.DTEHelper.OutPutMessage(string.Format("服务器{0}已连接...", ip), true);
                            Succ("服务器可以正常连接....");
                            FormMain fm = new FormMain();
                            fm.Server = ip;
                            fm.ServerConnection = connectionStr;
                            this.Hide();
                            fm.ShowDialog();

                        }
                        else
                        {
                            Error("数据库链接错误，请确认服务器信息！");
                        }

                        break;
                    }
                }
            }
        }

        private void lstServer_DoubleClick(object sender, EventArgs e)
        {
            btnNext_Click(sender, e);
        }
    }
}
